<template>
  <div class="risk-management-container">
    <el-card class="filter-card">
      <div class="filter-header">
        <h2>风险用户管理</h2>
        <el-button type="primary" @click="batchDetection">批量风险检测</el-button>
      </div>
      <el-form :inline="true" :model="filterForm" class="filter-form">
        <el-form-item label="风险等级">
          <el-select v-model="filterForm.riskLevel" placeholder="选择风险等级" clearable>
            <el-option label="低风险" :value="0" />
            <el-option label="中风险" :value="1" />
            <el-option label="高风险" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="风险类型">
          <el-select v-model="filterForm.riskType" placeholder="选择风险类型" clearable>
            <el-option label="身份冒用" :value="1" />
            <el-option label="资金异常" :value="2" />
            <el-option label="地域冲突" :value="3" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleFilter">筛选</el-button>
          <el-button @click="resetFilter">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card class="table-card">
      <el-table :data="riskUserList" style="width: 100%" v-loading="tableLoading">
        <el-table-column prop="userAddress" label="用户地址" width="180" show-overflow-tooltip />
        <el-table-column prop="score" label="风险评分" width="100">
          <template #default="scope">
            <el-tag :type="getScoreTagType(scope.row.score)">{{ scope.row.score }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="riskLevel" label="风险等级" width="100">
          <template #default="scope">
            <el-tag :type="getRiskLevelTagType(scope.row.riskLevel)">{{ getRiskLevelText(scope.row.riskLevel) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="riskTypeDesc" label="风险类型" width="120" />
        <el-table-column prop="evidenceSummary" label="风险证据摘要" show-overflow-tooltip />
        <el-table-column prop="detectionTime" label="检测时间" width="180">
          <template #default="scope">
            {{ formatDateTime(scope.row.detectionTime) }}
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="250">
          <template #default="scope">
            <el-button link type="primary" size="small" @click="viewDetails(scope.row)">查看详情</el-button>
            <el-button link type="warning" size="small" @click="banUser(scope.row)">封禁用户</el-button>
            <el-button link type="success" size="small" @click="generateReport(scope.row)">生成报告</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 风险详情对话框 -->
    <el-dialog v-model="detailsDialogVisible" title="风险详情" width="50%">
      <div v-if="selectedRisk" class="risk-details">
        <div class="detail-item">
          <span class="label">用户地址:</span>
          <span>{{ selectedRisk.userAddress }}</span>
        </div>
        <div class="detail-item">
          <span class="label">风险评分:</span>
          <el-tag :type="getScoreTagType(selectedRisk.score)">{{ selectedRisk.score }}</el-tag>
        </div>
        <div class="detail-item">
          <span class="label">风险等级:</span>
          <el-tag :type="getRiskLevelTagType(selectedRisk.riskLevel)">{{ getRiskLevelText(selectedRisk.riskLevel) }}</el-tag>
        </div>
        <div class="detail-item">
          <span class="label">风险类型:</span>
          <span>{{ selectedRisk.riskTypeDesc }}</span>
        </div>
        <div class="detail-item">
          <span class="label">风险证据摘要:</span>
          <span>{{ selectedRisk.evidenceSummary }}</span>
        </div>
        <div class="detail-item">
          <span class="label">检测时间:</span>
          <span>{{ formatDateTime(selectedRisk.detectionTime) }}</span>
        </div>
        <div class="detail-item">
          <span class="label">建议处置措施:</span>
          <span>{{ selectedRisk.suggestedAction }}</span>
        </div>
        <div class="detail-item evidence-details">
          <span class="label">详细证据:</span>
          <el-collapse>
            <el-collapse-item title="查看详细证据">
              <div v-for="(evidence, index) in selectedRisk.evidenceDetails" :key="index" class="evidence-item">
                <el-tag size="small" type="info">证据 {{ index + 1 }}</el-tag>
                <p>{{ evidence }}</p>
              </div>
            </el-collapse-item>
          </el-collapse>
        </div>
      </div>
    </el-dialog>

    <!-- 封禁用户对话框 -->
    <el-dialog v-model="banDialogVisible" title="封禁用户" width="40%">
      <el-form :model="banForm" label-width="120px">
        <el-form-item label="用户地址">
          <el-input v-model="banForm.userAddress" disabled />
        </el-form-item>
        <el-form-item label="用户ID">
          <el-input v-model="banForm.userId" placeholder="请输入用户ID" />
        </el-form-item>
        <el-form-item label="封禁类型">
          <el-select v-model="banForm.banType" placeholder="请选择封禁类型">
            <el-option :value="1" label="资金操作" />
            <el-option :value="2" label="敏感操作" />
            <el-option :value="3" label="全部封禁" />
          </el-select>
        </el-form-item>
        <el-form-item label="封禁时长">
          <el-radio-group v-model="banForm.banDuration">
            <el-radio :label="'temporary'">临时封禁</el-radio>
            <el-radio :label="'permanent'">永久封禁</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="到期时间" v-if="banForm.banDuration === 'temporary'">
          <el-date-picker
            v-model="banForm.expiryTime"
            type="datetime"
            placeholder="选择封禁到期时间"
            format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>
        <el-form-item label="封禁原因">
          <el-input
            v-model="banForm.reason"
            type="textarea"
            :rows="3"
            placeholder="请输入封禁原因"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="banDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitBan">确认封禁</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 解封用户对话框 -->
    <el-dialog v-model="unbanDialogVisible" title="解封用户" width="40%">
      <el-form :model="unbanForm" label-width="120px">
        <el-form-item label="用户ID">
          <el-input v-model="unbanForm.userId" placeholder="请输入用户ID" />
        </el-form-item>
        <el-form-item label="解封类型">
          <el-select v-model="unbanForm.banType" placeholder="请选择解封类型" clearable>
            <el-option :value="1" label="资金操作" />
            <el-option :value="2" label="敏感操作" />
            <el-option :value="3" label="全部解封" />
          </el-select>
        </el-form-item>
        <el-form-item label="解封原因">
          <el-input
            v-model="unbanForm.reason"
            type="textarea"
            :rows="3"
            placeholder="请输入解封原因"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="unbanDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitUnban">确认解封</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import myAxios from '../../plugins/myAxios.js';
import { formatDateTime } from '../../common/commonFunc.ts';

// 表格数据和加载状态
const riskUserList = ref([]);
const tableLoading = ref(false);
const total = ref(0);
const currentPage = ref(1);
const pageSize = ref(10);

// 筛选表单
const filterForm = reactive({
  riskLevel: null,
  riskType: null
});

// 对话框显示状态
const detailsDialogVisible = ref(false);
const banDialogVisible = ref(false);
const unbanDialogVisible = ref(false);
const selectedRisk = ref(null);

// 封禁表单
const banForm = reactive({
  userId: '',
  userAddress: '',
  banType: 3,
  banDuration: 'temporary',
  expiryTime: null,
  reason: ''
});

// 解封表单
const unbanForm = reactive({
  userId: '',
  banType: 3,
  reason: ''
});

// 获取风险用户列表
const fetchRiskUsers = async () => {
  tableLoading.value = true;
  try {
    // 这里应该调用后端API获取风险用户列表
    // 由于没有现成的API，这里模拟一些数据
    const response = await myAxios.post('/fraud/batch');
    if (response.data.code === 200) {
      riskUserList.value = response.data.data;
      total.value = response.data.data.length;
    } else {
      ElMessage.error(`获取风险用户列表失败：${response.data.msg}`);
    }
  } catch (error) {
    ElMessage.error(`获取风险用户列表失败：${error.message}`);
  } finally {
    tableLoading.value = false;
  }
};

// 批量风险检测
const batchDetection = async () => {
  try {
    const response = await myAxios.post('/fraud/batch');
    if (response.data.code === 200) {
      ElMessage.success('批量风险检测完成');
      fetchRiskUsers();
    } else {
      ElMessage.error(`批量风险检测失败：${response.data.msg}`);
    }
  } catch (error) {
    ElMessage.error(`批量风险检测失败：${error.message}`);
  }
};

// 筛选处理
const handleFilter = () => {
  currentPage.value = 1;
  fetchRiskUsers();
};

// 重置筛选
const resetFilter = () => {
  filterForm.riskLevel = null;
  filterForm.riskType = null;
  handleFilter();
};

// 分页处理
const handleSizeChange = (val) => {
  pageSize.value = val;
  fetchRiskUsers();
};

const handleCurrentChange = (val) => {
  currentPage.value = val;
  fetchRiskUsers();
};

// 查看详情
const viewDetails = (row) => {
  selectedRisk.value = row;
  detailsDialogVisible.value = true;
};

// 封禁用户
const banUser = (row) => {
  banForm.userAddress = row.userAddress;
  banForm.userId = ''; // 需要用户输入ID
  banForm.banType = 3;
  banForm.banDuration = 'temporary';
  banForm.expiryTime = new Date(new Date().getTime() + 7 * 24 * 60 * 60 * 1000); // 默认7天
  banForm.reason = row.evidenceSummary || '';
  banDialogVisible.value = true;
};

// 提交封禁
const submitBan = async () => {
  if (!banForm.userId) {
    ElMessage.warning('请输入用户ID');
    return;
  }
  
  if (banForm.banDuration === 'temporary' && !banForm.expiryTime) {
    ElMessage.warning('请选择封禁到期时间');
    return;
  }
  
  try {
    const params = {
      userId: banForm.userId,
      banType: banForm.banType
    };
    
    if (banForm.banDuration === 'temporary') {
      params.expiryTime = formatDateTime(banForm.expiryTime);
    }
    
    const response = await myAxios.post('/user/ban', null, { params });
    if (response.data.code === 200) {
      ElMessage.success('用户封禁成功');
      banDialogVisible.value = false;
      fetchRiskUsers();
    } else {
      ElMessage.error(`用户封禁失败：${response.data.msg}`);
    }
  } catch (error) {
    ElMessage.error(`用户封禁失败：${error.message}`);
  }
};

// 打开解封对话框
const openUnbanDialog = () => {
  unbanForm.userId = '';
  unbanForm.banType = 3;
  unbanForm.reason = '';
  unbanDialogVisible.value = true;
};

// 提交解封
const submitUnban = async () => {
  if (!unbanForm.userId) {
    ElMessage.warning('请输入用户ID');
    return;
  }
  
  try {
    const params = {
      userId: unbanForm.userId
    };
    
    if (unbanForm.banType) {
      params.banType = unbanForm.banType;
    }
    
    const response = await myAxios.post('/user/unban', null, { params });
    if (response.data.code === 200) {
      ElMessage.success('用户解封成功');
      unbanDialogVisible.value = false;
      fetchRiskUsers();
    } else {
      ElMessage.error(`用户解封失败：${response.data.msg}`);
    }
  } catch (error) {
    ElMessage.error(`用户解封失败：${error.message}`);
  }
};

// 生成风险报告
const generateReport = async (row) => {
  try {
    const response = await myAxios.get(`/fraud/risk-report/${row.userAddress}`);
    if (response.data.code === 200) {
      ElMessage.success('风险报告生成成功');
      // 这里可以添加下载报告或显示报告的逻辑
      ElMessageBox.alert(
        `<div style="max-height: 400px; overflow-y: auto;">
          <h3>风险报告</h3>
          <p><strong>用户地址:</strong> ${response.data.data.userAddress}</p>
          <p><strong>风险评分:</strong> ${response.data.data.score}</p>
          <p><strong>风险等级:</strong> ${getRiskLevelText(response.data.data.riskLevel)}</p>
          <p><strong>风险类型:</strong> ${response.data.data.riskTypeDesc}</p>
          <p><strong>风险证据摘要:</strong> ${response.data.data.evidenceSummary}</p>
          <p><strong>建议处置措施:</strong> ${response.data.data.suggestedAction}</p>
          <p><strong>检测时间:</strong> ${formatDateTime(response.data.data.detectionTime)}</p>
          <h4>详细证据:</h4>
          <ul>
            ${response.data.data.evidenceDetails.map(item => `<li>${item}</li>`).join('')}
          </ul>
        </div>`,
        '风险报告',
        {
          dangerouslyUseHTMLString: true,
          confirmButtonText: '关闭'
        }
      );
    } else {
      ElMessage.error(`生成风险报告失败：${response.data.msg}`);
    }
  } catch (error) {
    ElMessage.error(`生成风险报告失败：${error.message}`);
  }
};

// 获取风险等级文本
const getRiskLevelText = (level) => {
  switch (level) {
    case 0: return '低风险';
    case 1: return '中风险';
    case 2: return '高风险';
    default: return '未知风险';
  }
};

// 获取风险等级标签类型
const getRiskLevelTagType = (level) => {
  switch (level) {
    case 0: return 'success';
    case 1: return 'warning';
    case 2: return 'danger';
    default: return 'info';
  }
};

// 获取评分标签类型
const getScoreTagType = (score) => {
  if (score < 30) return 'success';
  if (score < 70) return 'warning';
  return 'danger';
};

onMounted(() => {
  fetchRiskUsers();
});
</script>

<style scoped>
.risk-management-container {
  padding: 20px;
}

.filter-card,
.table-card {
  margin-bottom: 20px;
}

.filter-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.risk-details {
  padding: 10px;
}

.detail-item {
  margin-bottom: 15px;
  display: flex;
  align-items: flex-start;
}

.label {
  font-weight: bold;
  width: 120px;
  display: inline-block;
}

.evidence-details {
  flex-direction: column;
}

.evidence-item {
  margin-top: 10px;
  padding: 10px;
  background-color: #f8f8f8;
  border-radius: 4px;
}

.evidence-item p {
  margin-top: 5px;
  margin-bottom: 0;
}
</style>